package com.foo.RealTimeData;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.Entity.RealTimeData;

import com.foo.Entity.TickerInfoData;

import com.foo.constants.UIMessages;


import javax.servlet.RequestDispatcher;

/**
 * Servlet implementation class RealTimeDataServlet
 */
public class RealTimeDataServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	
	String[] resultString = null;
	Queue queue = null;
	QueueConnectionFactory factory = null;
	QueueConnection connection = null;
	QueueSender sender = null;
	TopicSession session = null;
	String[] data_to_be_passed=null;
	String retrieved_data="";
	MessageConsumer reciever=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RealTimeDataServlet() {
        super();
    }
    
    public void init()
    {
    	try
    	{
    	Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
		Context ctx;
		ctx = new InitialContext(props);

		TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("XAConnectionFactory");
		TopicConnection connection = factory.createTopicConnection();
		session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
		
		Topic topic = (Topic) ctx.lookup("topic/MyRealTimeTopic");
		reciever = session.createConsumer(topic);
		System.out.println("Client started waiting for Server message");
		connection.start();
    	}
    	catch(Exception e)
    	{
    	e.printStackTrace();
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession(true);
		RequestDispatcher dispatcher;
		RealTimeData tickerdata = null;

		TickerInfoData tickerinfo = null;
		RealTimeClient data = new RealTimeClient();

		
		session.setAttribute("realdatareceived","no");
		//get request parameters
		String tickername = request.getParameter("RealTimeCompany");
		System.out.println("Received Request is: " +tickername);
		
		//Validate if all the input string entered
		if((tickername.equalsIgnoreCase("")))
		{
			session.setAttribute("ServerMessage", UIMessages.REQUIRED_FIELD);
			dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
			dispatcher.forward(request, response);
		}
		else
		{
			session.setAttribute("ServerMessage",null);
		}
		
		java.sql.Timestamp sqltoDate = new java.sql.Timestamp(System.currentTimeMillis());
		data.realtime(tickername,sqltoDate);
		System.out.println("The Date-Time being passed is: " +sqltoDate.toString());
		try {
			while (true) 
			{
		    	Message m = reciever.receive(0);
				
		    	if (m != null) 
		    	{ 
		    		if (m instanceof TextMessage) 
		    		{ 
		            TextMessage message = (TextMessage) m; 
		            System.out.println("Reading message: " + message.getText()); 
		            retrieved_data = message.getText();
		            resultString = retrieved_data.split(","); 
		 			int total_size = resultString .length;
		 			System.out.println("the size of data at client end "+ total_size);
		            break;
		    		}	 
		    		else 
		        	{ 
		            break; 
		        	} 
		    	}
			}
			
			}catch (JMSException e) {
				e.printStackTrace();
				dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
				dispatcher.forward(request, response);
			}
			
		System.out.println("values length: " +resultString.length);
		
		if(resultString != null)
		{
			for(int i=0;i<resultString.length;i+=9) //i+=9
			{
			if(resultString[i].equals("") || resultString[i] == null)
			{
				System.out.println("No more data to print");
				break;
			}
			else
			{
			tickerdata = new RealTimeData();
			tickerinfo = new TickerInfoData();
			tickerdata.setTicker_symbol(resultString[i]);
			tickerdata.setOpen_value(Double.parseDouble(resultString[i+1]));
			tickerinfo.setCompany(resultString[1+3]);
			tickerinfo.setSector_name(resultString[i+4]);
			tickerinfo.setIndustry(resultString[i+5]);
			tickerinfo.setCountry(resultString[i+6]);
			tickerinfo.setState(resultString[i+7]);
			tickerinfo.setMarket_cap(Double.parseDouble(resultString[i+8]));
			
			session.setAttribute("realdatareceived","yes");
			session.setAttribute("realtimedata", tickerdata);
			session.setAttribute("tickerinfodata", tickerinfo);
			session.setAttribute("timevalue", resultString[i+2]);
			}
			}
		}
		else
		{	
			session.setAttribute("realdatareceived","no");
			System.out.println("No message returned");
		}
		
		System.out.println("Exited Loop");
		dispatcher = getServletContext().getRequestDispatcher("/realtime.jsp");
		dispatcher.forward(request, response);
	}
}
